package message.handler;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.Collection;

import net.VirtualQueue;

public class BackOnlineHandler implements Runnable {

	private String username;

	public BackOnlineHandler(String username) {
		this.username = username;
	}

	@Override
	public synchronized void run() {
		try {
			Thread.sleep(1000);
		} catch (InterruptedException e1) {
			e1.printStackTrace();
		}
		VirtualQueue vq = VirtualQueue.obtainVirtualQueue();
		Collection<String> storedMessages = vq.popStoredMessagesTo(username);

		File cloudFolder = new File(PersistentMessageHandler.folder);

		for (String filename : storedMessages) {

			String xmlRappresentation;
			try {
				xmlRappresentation = this.getXMLFromFile(filename, cloudFolder);
				new Thread(new MessageHandler(xmlRappresentation)).start();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

	}

	private String getXMLFromFile(String filename, File cloudFolder)
			throws IOException {
		File persistentMessage = new File(cloudFolder, filename);
		String xmlRappresentation = "";
		if (!persistentMessage.exists())
			throw new IOException();
		try {
			FileReader fl = new FileReader(persistentMessage);
			BufferedReader br = new BufferedReader(fl);
			String line = null;
			while ((line = br.readLine()) != null)
				xmlRappresentation += line;

			br.close();

			if (persistentMessage.exists())
				persistentMessage.delete();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return xmlRappresentation;
	}

}
